<template>
  <div class="app-container">
    <div class="search-input-size" style="margin-bottom: 4px;">
      <el-date-picker
        v-model="searchDate"
        placeholder="选择时间"
        type="month"
        @change="dateChange"
        value-format="yyyy-MM-dd"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-button type="primary" @click="fetchData()">查询</el-button>
    </div>
    <el-row>
      <div style="padding: 10px;background:#FED966;color: red;">
        {{ parseTime(currentDate, '{y}-{m}') }}
      </div>
    </el-row>
    <template v-if="list === null">
      <div style="padding: 10px;">暂无数据</div>
    </template>
  <template v-for="item in list">
    <div class="group-name">{{ item.groupName }}</div>
    <el-table ref="multipleTable" :data="item.groupList" :summary-method="getSummaries" header-row-class-name="header-row" show-summary
              v-loading="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column label="优惠码" align="center">
        <template slot-scope="scope">
          {{scope.row.name == '' ? '-' : scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column v-for="col in colList" :key="col.colName" :label="col.colName+''" align="center">
        <template slot-scope="scope">
          {{scope.row[col.col] }}
        </template>
      </el-table-column>
      <el-table-column label="合计" align="center">
        <template slot-scope="scope">
          {{totalRowNum(scope.row)}}
        </template>
      </el-table-column>
    </el-table>
  </template>
    <el-row>
      <div style="padding: 10px 50px;background:#FED966;color: red;margin-top:10px;text-align: right;">
        总计：{{ totalNum }}
      </div>
    </el-row>
    <el-button-group style="margin-top: 10px;">
      <el-button type="primary" size="mini" @click="prevDay()">上一月</el-button>
      <el-button type="primary" size="mini" @click="nextDay()">下一月</el-button>
    </el-button-group>
    <!--<div  style="padding: 1% 0%;text-align: right;background:#FED966; ">
      <label>总计</label>
      <label style="margin-right: 2%;" id="total">0</label>
    </div>-->

  </div>
</template>

<script>
  import { parseTime } from '@/utils/index'
  import { sheetApi } from '@/api/sheet'
  const zxData = require('@/../static/zx.json')
  export default {
    data() {
      return {
        listLoading: false,
        colList: [],
        list: {},
        totalNum: 0,
        searchDate: '',
        currentDate: '',
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now()
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          }]
        }
      }
    },
    created() {
      this.fetchData()
      console.log(zxData)
    },
    methods: {
      fetchData() {
        this.listLoading = true
        sheetApi.getMonthlySales(this.searchDate).then(response => {
          this.list = this.makeList(response.data.list)
          this.currentDate = response.data.date
          this.listLoading = false
        })
      },
      makeList(list) {
        this.totalNum = 0
        /**
         * 表格列表
         * [
         *    {
         *        colName: '0.01',
         *        col: 'col1'
         *    },
         *    {
         *        colName: '1990',
         *        col: 'col2'
         *    }
         * ]
         * 表格数据
         * {
         *     "曾欢组": {
         *         groupName: "曾欢组",
         *         groupList: [
         *             {
         *                 name: "曾欢",
         *                 col1: 0,
         *                 col2: 0
         *             }
         *         ]
         *     }
         * }
         * @type {number}
         */
        if (list.length === 0) {
          return null
        }
        let totalNum = 0
        const collist = []
        let colNum = 0
        list.forEach((column, index) => {
          let findCol = false
          collist.forEach((item, i) => {
            if (item.colName === column.payMoney) {
              findCol = true
              return true
            }
          })
          if (!findCol) {
            const col = {
              colName: column.payMoney,
              col: 'col' + colNum
            }
            collist.push(col)
          }
          colNum += 1
        })
        this.colList = collist
        const finalList = {}
        list.forEach((column, index) => {
          let curRow = ''
          collist.forEach((item, i) => {
            if (item.colName === column.payMoney) {
              curRow = item.col
            }
          })
          totalNum += column.num
          console.log(index)
          const name = (column.coupon ? column.coupon : '') + (column.name ? column.name : '')
          if (column.name) {
            let findZX = false
            for (let i = 0; i < zxData.length; i++) {
              if (zxData[i].name === column.name) {
                findZX = true
                if (!finalList[zxData[i].group]) {
                  finalList[zxData[i].group] = {
                    groupName: zxData[i].group,
                    groupList: []
                  }
                }
                let hadMember = false
                for (let j = 0; j < finalList[zxData[i].group].groupList.length; j++) {
                  if (finalList[zxData[i].group].groupList[j].name === name) {
                    hadMember = true
                    finalList[zxData[i].group].groupList[j][curRow] = column.num
                    break
                  }
                }
                if (!hadMember) {
                  const member = {
                    name: name
                  }
                  collist.forEach((item, i) => {
                    member[item.col] = 0
                  })
                  // const member = {
                  //   name: name,
                  //   zero: 0,
                  //   nine: 0,
                  //   twelve: 0,
                  //   sixteen: 0,
                  //   eighteen: 0
                  // }
                  member[curRow] = column.num
                  finalList[zxData[i].group].groupList.push(member)
                }
                break
              }
            }
            if (!findZX) {
              if (!finalList['其他']) {
                finalList['其他'] = {
                  groupName: '其他',
                  groupList: []
                }
              }
              let hadMember = false
              for (let j = 0; j < finalList['其他'].groupList.length; j++) {
                if (finalList['其他'].groupList[j].name === name) {
                  hadMember = true
                  finalList['其他'].groupList[j][curRow] = column.num
                  break
                }
              }
              if (!hadMember) {
                const member = {
                  name: name
                }
                collist.forEach((item, i) => {
                  member[item.col] = 0
                })
                member[curRow] = column.num
                finalList['其他'].groupList.push(member)
              }
            }
          } else {
            if (!finalList['其他']) {
              finalList['其他'] = {
                groupName: '其他',
                groupList: []
              }
            }
            let hadMember = false
            for (let j = 0; j < finalList['其他'].groupList.length; j++) {
              if (finalList['其他'].groupList[j].name === name) {
                hadMember = true
                finalList['其他'].groupList[j][curRow] = column.num
                break
              }
            }
            if (!hadMember) {
              const member = {
                name: name
              }
              collist.forEach((item, i) => {
                member[item.col] = 0
              })
              member[curRow] = column.num
              finalList['其他'].groupList.push(member)
            }
          }
        })
        this.totalNum = totalNum
        return finalList
      },
      getSummaries(param) {
        const { columns, data } = param
        console.log(columns)
        console.log(data)
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[0] = '汇总'
            return
          }
          let num = 0
          data.forEach((col, i) => {
            if (columns.length - 1 === index) {
              this.colList.forEach((c, index2) => {
                // num += row[col.col]
                num += col[c.col]
              })
            } else {
              this.colList.forEach((c, index2) => {
                // num += row[col.col]
                if (column.label === c.colName + '') {
                  num += col[c.col]
                  return true
                }
              })
            }
          })
          sums[index] = num
        })
        return sums
      },
      // var preDate = new Date(curDate.getTime() - 24*60*60*1000); //前一天
      // var nextDate = new Date(curDate.getTime() + 24*60*60*1000); //后一天
      prevDay() {
        const dateArr = this.currentDate.split('-')
        if (dateArr[1] === '01') {
          dateArr[0] = Number(dateArr[0]) - 1 + ''
          dateArr[1] = '12'
        } else {
          dateArr[1] = Number(dateArr[1]) - 1
          if (dateArr[1] < 10) {
            dateArr[1] = '0' + dateArr[1]
          }
        }
        const preMonth = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
        this.searchDate = parseTime(new Date(preMonth).getTime(), '{y}-{m}-{d}')
        this.fetchData()
      },
      nextDay() {
        const dateArr = this.currentDate.split('-')
        if (dateArr[1] === '12') {
          dateArr[0] = Number(dateArr[0]) + 1 + ''
          dateArr[1] = '01'
        } else {
          dateArr[1] = Number(dateArr[1]) + 1
          if (dateArr[1] < 10) {
            dateArr[1] = '0' + dateArr[1]
          }
        }
        const preMonth = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
        if (new Date(preMonth).getTime() > new Date().getTime()) {
          this.$message({ message: '最高日期不能超过当前月.', type: 'warning' })
          return
        }
        this.searchDate = parseTime(new Date(preMonth).getTime(), '{y}-{m}-{d}')
        this.fetchData()
      },
      dateChange() {
        const now = new Date()
        if (new Date(this.searchDate).getTime() > now.getTime()) {
          this.$message({ message: '最高日期不能超过当前月.', type: 'warning' })
          this.searchDate = now
        }
      },
      parseTime(date, format) {
        return parseTime(new Date(date), format)
      },
      totalRowNum(row) {
        console.log(row)
        let num = 0
        this.colList.forEach((col, index) => {
          num += row[col.col]
        })
        return num
      }
    }
  }
</script>
<style>
  .header-row th {
    background-color: #f5f7fa;
  }
  .group-name {
    border: 1px solid #ebeef5;
    border-bottom: none;
    padding: 10px;
    background-color: #cccccc;
    margin-top: 10px;
  }
</style>
